package com.sj.common.wechatUtils;

import org.apache.commons.lang3.StringUtils;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.util.Map;

public class HttpKit {
	private static final String DEFAULT_CHARSET = "UTF-8";
	private static String get(String url)
    throws NoSuchAlgorithmException, NoSuchProviderException, IOException, KeyManagementException
  {
    StringBuffer bufferRes = null;
    TrustManager[] tm = { new MyX509TrustManager() };
    SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
    sslContext.init(null, tm, new SecureRandom());
    
    SSLSocketFactory ssf = sslContext.getSocketFactory();
    
    URL urlGet = new URL(url);
    HttpsURLConnection http = (HttpsURLConnection)urlGet.openConnection();
    
    http.setConnectTimeout(25000);
    http.setReadTimeout(25000);
    http.setRequestMethod("GET");
    http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    http.setSSLSocketFactory(ssf);
    http.setDoOutput(true);
    http.setDoInput(true);
    http.connect();
    
    InputStream in = http.getInputStream();
    BufferedReader read = new BufferedReader(new InputStreamReader(in, "UTF-8"));
    String valueString = null;
    bufferRes = new StringBuffer();
    while ((valueString = read.readLine()) != null) {
      bufferRes.append(valueString);
    }
    in.close();
    if (http != null) {
      http.disconnect();
    }
    return bufferRes.toString();
  }
  
  public static String get(String url, Boolean https)
    throws NoSuchAlgorithmException, NoSuchProviderException, IOException, KeyManagementException
  {
    if ((https != null) && (https.booleanValue())) {
      return get(url);
    }
    StringBuffer bufferRes = null;
    URL urlGet = new URL(url);
    HttpURLConnection http = (HttpURLConnection)urlGet.openConnection();
    
    http.setConnectTimeout(25000);
    
    http.setReadTimeout(25000);
    http.setRequestMethod("GET");
    http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    http.setDoOutput(true);
    http.setDoInput(true);
    http.connect();
    
    InputStream in = http.getInputStream();
    BufferedReader read = new BufferedReader(new InputStreamReader(in, "UTF-8"));
    String valueString = null;
    bufferRes = new StringBuffer();
    while ((valueString = read.readLine()) != null) {
      bufferRes.append(valueString);
    }
    in.close();
    if (http != null) {
      http.disconnect();
    }
    return bufferRes.toString();
  }
  
  public static String get(String url, Map<String, String> params)
    throws KeyManagementException, NoSuchAlgorithmException, NoSuchProviderException, IOException
  {
    return get(initParams(url, params));
  }
  
  public static String post(String url, String params)
    throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException
  {
    StringBuffer bufferRes = null;
    TrustManager[] tm = { new MyX509TrustManager() };
    SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
    sslContext.init(null, tm, new SecureRandom());
    
    SSLSocketFactory ssf = sslContext.getSocketFactory();
    URL urlGet = new URL(url);
    HttpsURLConnection http = (HttpsURLConnection)urlGet.openConnection();
    
    http.setConnectTimeout(25000);
    
    http.setReadTimeout(25000);
    http.setRequestMethod("POST");
    http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    http.setSSLSocketFactory(ssf);
    http.setDoOutput(true);
    http.setDoInput(true);
    http.connect();
    OutputStream out = http.getOutputStream();
    out.write(params.getBytes("UTF-8"));
    out.flush();
    out.close();
    InputStream in = http.getInputStream();
    BufferedReader read = new BufferedReader(new InputStreamReader(in, "UTF-8"));
    String valueString = null;
    bufferRes = new StringBuffer();
    while ((valueString = read.readLine()) != null) {
      bufferRes.append(valueString);
    }
    in.close();
    if (http != null) {
      http.disconnect();
    }
    return bufferRes.toString();
  }
  
  public static String upload(String url, File file)
    throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException
  {
    String BOUNDARY = "----WebKitFormBoundaryiDGnV9zdZA1eM1yL";
    StringBuffer bufferRes = null;
    URL urlGet = new URL(url);
    HttpURLConnection conn = (HttpURLConnection)urlGet.openConnection();
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setUseCaches(false);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("connection", "Keep-Alive");
    conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36");
    conn.setRequestProperty("Charsert", "UTF-8");
    conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
    
    OutputStream out = new DataOutputStream(conn.getOutputStream());
    byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
    StringBuilder sb = new StringBuilder();
    sb.append("--");
    sb.append(BOUNDARY);
    sb.append("\r\n");
    sb.append("Content-Disposition: form-data;name=\"media\";filename=\"" + file.getName() + "\"\r\n");
    sb.append("Content-Type:application/octet-stream\r\n\r\n");
    byte[] data = sb.toString().getBytes();
    out.write(data);
    DataInputStream fs = new DataInputStream(new FileInputStream(file));
    int bytes = 0;
    byte[] bufferOut = new byte[1024];
    while ((bytes = fs.read(bufferOut)) != -1) {
      out.write(bufferOut, 0, bytes);
    }
    out.write("\r\n".getBytes());
    fs.close();
    out.write(end_data);
    out.flush();
    out.close();
    

    InputStream in = conn.getInputStream();
    BufferedReader read = new BufferedReader(new InputStreamReader(in, "UTF-8"));
    String valueString = null;
    bufferRes = new StringBuffer();
    while ((valueString = read.readLine()) != null) {
      bufferRes.append(valueString);
    }
    in.close();
    if (conn != null) {
      conn.disconnect();
    }
    return bufferRes.toString();
  }
  
  private static String initParams(String url, Map<String, String> params)
  {
    if ((params == null) || (params.isEmpty())) {
      return url;
    }
    StringBuilder sb = new StringBuilder(url);
    if (url.indexOf("?") == -1) {
      sb.append("?");
    } else {
      sb.append("&");
    }
    boolean first = true;
    for (Map.Entry<String, String> entry : params.entrySet())
    {
      if (first) {
        first = false;
      } else {
        sb.append("&");
      }
      String key = (String)entry.getKey();
      String value = (String)entry.getValue();
      sb.append(key).append("=");
      if (StringUtils.isNotEmpty(value)) {
        try
        {
          sb.append(URLEncoder.encode(value, "UTF-8"));
        }
        catch (UnsupportedEncodingException e)
        {
          e.printStackTrace();
        }
      }
    }
    return sb.toString();
  }
  
  public static void main(String[] args)
  {
    String fname = "dsasdas.mp4";
    String s = fname.substring(0, fname.lastIndexOf("."));
    String f = fname.substring(s.length() + 1);
    System.out.println(f);
  }
}
